import os
from service.sjxz import zddr_upload
from config import ini_op


def run(llq, hszb):
  nd, folderpath = ini_op.getinivalue('kmzd_config', 'kjnd', 'folderpath')
  os.makedirs(folderpath, exist_ok=True)
  browser, context, page = llq
  page.click('#toolbar_header_function')
  page.fill('#search', '账簿科目定义')
  page.wait_for_timeout(2000)
  try:
      page.wait_for_selector('ul.search--result-list', timeout=2000)
  except Exception:
      page.click('.header--search')
  page.locator('ul.search--result-list li').first.click()

  page.click('#textBox_year .f-icon-lookup')
  page.locator('.lookup-tabs-content [title="'+nd+'"]').dblclick()

  page.click('#textBox_ledgerID .f-icon-lookup')
  page.locator('.lookup-tabs-content [name="input-group-value"]').fill(hszb)
  page.locator('.lookup-tabs-content [name="input-group-value"]').press('Enter')
  page.wait_for_timeout(1000)
  page.locator('[id^=rownode] .align-items-center span:text-matches(\"^'+hszb+'$\")').last.dblclick()

  page.locator('#button-filter').last.click()
  page.wait_for_timeout(1000)
  try:
    page.locator('div[id^=toolbar-group]').last.click(timeout=1000)
  except Exception:
     pass

  with page.expect_download(timeout=600000) as download_info:
    page.locator('#button-ExcelExport').last.click()
    download = download_info.value
    filepath = os.path.join(folderpath, nd+hszb+'科目字典导出'+download.suggested_filename[-5:])
    download.save_as(filepath)

  zddr_upload.file_uploads(filepath)
  page.click('[title="账簿科目定义"] div.nav-link-close')


